package com.example.joblinker.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

/**
 * JWT工具类
 */
@Component
public class JwtUtil {

    private static String secret;
    private static Long expire;

    @Value("${jwt.secret}")
    public void setSecret(String secret) {
        JwtUtil.secret = secret;
    }

    @Value("${jwt.expire}")
    public void setExpire(Long expire) {
        JwtUtil.expire = expire;
    }

    private static Key getSigningKey() {
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 生成token
     */
    public static String generateToken(Long userId) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + expire);
        return Jwts.builder()
                .setSubject(userId.toString())
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * 生成包含用户角色的token
     */
    public static String generateToken(Long userId, Integer role) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + expire);
        
        Map<String, Object> claims = new HashMap<>();
        claims.put("sub", userId.toString());
        claims.put("role", role);
        
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * 解析token获取用户ID
     */
    public static Long getUserId(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
       
        String subject = claims.getSubject();
        if (subject != null) {
            return Long.parseLong(subject);
        }
        
        // 如果subject为null，可能是因为设置了claims，尝试从claims中获取userId
        Object userIdObj = claims.get("sub");
        if (userIdObj != null) {
            return Long.parseLong(userIdObj.toString());
        }
        
        return null;
    }

    /**
     * 获取token中的用户角色
     */
    public static Integer getUserRole(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
        
        Object roleObj = claims.get("role");
        if (roleObj != null) {
            return Integer.parseInt(roleObj.toString());
        }
        return null;
    }

    /**
     * 验证token
     */
    public static boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取用户ID（为了兼容性）
     */
    public Long getUserIdFromToken(String token) {
        return getUserId(token);
    }

    /**
     * 从请求中获取用户ID
     */
    public Long getUserIdFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                Claims claims = Jwts.parserBuilder()
                        .setSigningKey(getSigningKey())
                        .build()
                        .parseClaimsJws(token)
                        .getBody();
                return Long.parseLong(claims.getSubject());
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
    
    /**
     * 从请求中获取用户角色
     */
    public Integer getUserRoleFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                Claims claims = Jwts.parserBuilder()
                        .setSigningKey(getSigningKey())
                        .build()
                        .parseClaimsJws(token)
                        .getBody();
                
                Object roleObj = claims.get("role");
                if (roleObj != null) {
                    return Integer.parseInt(roleObj.toString());
                }
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
} 